﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DoubleH.Plugins;
using Table = FCNS.Data.Table;
using System.Data;
using System.ComponentModel;
using DoubleH.Utility;
using System.Windows.Controls.Primitives;
using System.Diagnostics;
using System.IO;
using DoubleH.Utility.Configuration;
using DoubleH.Utility.IO;
using FCNS.Data;
using System.Windows.Threading;

namespace DoubleH
{
    /// <summary>
    /// WorkArea.xaml 的交互逻辑
    /// </summary>
    public partial class WorkArea : Window
    {
        public WorkArea()
        {
            InitializeComponent();
        }

        Table.SysConfig sysConfig = null;
        public MenuItemBinding selectedMenu = null;

        PluginManager pluginManager = new PluginManager();
        public PluginManager PluginManager { get { return pluginManager; } }
        /// <summary>
        /// 主机面右上角菜单
        /// </summary>
        public Menu ITopMenu { get { return TopMenu; } }
        /// <summary>
        /// 主界面右下角菜单
        /// </summary>
        public Menu IBottomMenu { get { return bottomMenu; } }

        public void Init()
        {
            if (!NormalUtility.ShowLoginWindowSuccess(Table.UserS.EnumFlag.操作员))
            {
                System.Environment.Exit(0);
                return;
            }

            InitSysVar();
            InitUserVar();
            InitMenu();
            InitToolBar();
            InitTreeView();
            InitPagePanel();

            InitAlertMessage();
            InitCpuEvent();
            LoadInitUI();
            InitCheckDateIsChangedEvent();
            InitRefreshDataEvent();
            this.Dispatcher.BeginInvoke(new Action(InitPlugin));
        }

        private void InitSysVar()
        {
            sysConfig = Table.SysConfig.SysConfigParams;
            Table.StoreS.GetDefault();
            this.Title = FCNS.Data.DbDefine.SystemName;
            PrintFunction.Init();
            this.Closed += (s, ee) => ThisClose();
            this.SizeChanged+= (ss, ee) => PagePanelSizeChanged();
        }

        private void InitUserVar()
        {
            if (!loginUser.Content.ToString().Contains(Table.UserS.LoginUser._LoginName))
            {
                uCPagePanel1.LoadData(null, null);//如果不这样，切换用户就会显示旧用户的资料
                treeViewLeftMenu.ItemsSource = null;
            }

            this.loginUser.Content = "【当前登录用户:" + Table.UserS.LoginUser._LoginName + "】";
        }

        private void InitPlugin()
        {
            DefaultPluginHost pluginDefaultHost = new DefaultPluginHost();
            pluginDefaultHost.Initialize(this);
            pluginManager.Initialize(pluginDefaultHost);
            pluginManager.LoadAllExtension();
        }

        private void InitAlertMessage()
        {
            System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
            t.Interval = DoubleHConfig.UserConfig.AlertTime * 60000;
            t.Tick += (ss, ee) => GetMessageS();
            t.Start();
        }

        private void InitTreeView()
        {
            treeViewLeftMenu.MouseUp += (ss, ee) =>
            {
                if (treeViewLeftMenu.SelectedItems.Count == 0)
                    return;

                MenuItemBinding tb = treeViewLeftMenu.SelectedItems[0] as MenuItemBinding;
                if (tb == null)
                    return;
                if ( tb == selectedMenu)
                    return;

                if (tb.SubItems.Count != 0)//选中父类
                    selectedMenu = tb.SubItems[0];
                else
                    selectedMenu = tb;

                if (!string.IsNullOrEmpty(selectedMenu.DllFile))
                    TreeViewNodeClick();
            };
        }


        private void InitPagePanel()
        {
            #region 右键菜单
            MenuItem obj1 = new MenuItem() { Header = "添加到POS禁售列表" };
            uCPagePanel1.AddMenuItem(obj1);
            obj1.Click += (ss, ee) =>
            {
                if (uCPagePanel1.SelectedItem == null)
                    return;

                PosStopSale wss = new PosStopSale();
                wss.Init(PosStopSale.EnumFlag.Pos禁售商品, null, uCPagePanel1.SelectedItem as Table.ProductS);
                wss.ShowDialog();
            };

            MenuItem obj2 = new MenuItem() { Header = "编辑收银员列表" };
            uCPagePanel1.AddMenuItem(obj2);
            obj2.Click += (ss, ee) =>
            {
                if (uCPagePanel1.SelectedItem == null)
                    return;

                PosStopSale wss = new PosStopSale();
                wss.Init(PosStopSale.EnumFlag.Pos操作员, uCPagePanel1.SelectedItem as Table.PosS, null);
                wss.ShowDialog();
            };

            uCPagePanel1.ContextMenu.Opened += (ss, ee) =>
            {
                obj1.Visibility = (selectedMenu.TableText == DataTableText.可销售商品 ? Visibility.Visible : Visibility.Collapsed);
                obj2.Visibility = (selectedMenu.TableText == DataTableText.Pos机器号 ? Visibility.Visible : Visibility.Collapsed);
            };
            #endregion

            uCPagePanel1.ModeChanged += (ss, ee) => PagePanelModeChanged(ee);
            uCPagePanel1.ItemDoubleClick += (ss) => PagePanelItemDoubleClick();
            uCPagePanel1.ItemClick += (ee) => PagePanelItemClick(ee);
        }

        private void InitToolBar()
        {
            buttonNew.Click += (ss, ee) =>NewObj();
            labelPre.MouseDown += (ss, ee) => PreObj();
            labelNext.MouseDown += (ss, ee) => NewObj();
            labelSearch.MouseLeftButtonUp += (ss, ee) => SearchObjByWindow();
            textBoxSearch.TextChanged += (ss, ee) => SearchObjByText();
            //expanderMore.Expanded += (ss, ee) => ExpanderOpen();
            expanderMore.MouseLeave += (ss, ee) => ExpanderClose();
            button_import.Click += (ss, ee) => EventImport(); 
            button_Export.Click += (ss, ee) => EventExport();
            button_zuofei.Click += (ss, ee) => EventZuoFei();
            button_print.Click += (ss, ee) => Print();
            button_printList.Click += (ss, ee) => PrintList();
            button_refresh.Click += (ss, ee) => BeginBindData();
            button_edit.Click += (ss, ee) => EditObj();


            expanderConfig.Header = Table.UserS.LoginUser._GroupSName;
            expanderConfig.Expanded += (ss, ee) => ExpanderConfigOpen();
            expanderConfig.MouseLeave += (ss, ee) => ExpanderConfigClose();
            buttonAppConfig.Click += (ss, ee) => OpenSysconfig();
            buttonLogoff.Click += (ss, ee) => LoginOff();
            buttonHelp.Click += (ss, ee) => OpenHelp();
            buttonCalc.Click += (ss, ee) => OpenCalc();
        }

        /// <summary>
        /// 窗体加载后自动转到‘我的消息’界面和设置一些用户自己的配置
        /// </summary>
        private void LoadInitUI()
        {
            UserUIparams dgcb = DoubleHConfig.UserConfig.DataGridBinding.Find(f => f.TableText == DataTableText.待办事项);
            if (dgcb != null)
            {
                DataGridColumnHeaderBinding header = dgcb.Items.Find(f => f.BindingName.Contains("Flag"));
                if (header != null)
                {
                    header.BindingName = DoubleHConfig.UserConfig.ScheduleSUseImageForFlag ? "_Flag" : "Flag";
                    header.ColumnType = DoubleHConfig.UserConfig.ScheduleSUseImageForFlag ? "image" : "";
                }
            }
        }

        //private void HyperlinkClick(object sender, RoutedEventArgs e)
        //{
        //    Hyperlink obj = e.OriginalSource as Hyperlink;
        //    MessageBox.Show((obj == null).ToString());
        //    if (obj == null)
        //        return;

        //    Table.WuLiuS ws = uCPagePanel1.SelectedItem as Table.WuLiuS;
        //    MessageBox.Show((ws == null).ToString());
        //    if (ws == null)
        //        return;

        //    MessageBox.Show(ws._Http);
        //    Process.Start(ws._Http);
        //}

        private void InitCpuEvent()
        {
            Table.CPU.InsertTableObject += new Table.CPU.TableObject(CPU_InsertTableObject);
            Table.CPU.ShenHeTableObject += new Table.CPU.TableObject(CPU_ShenHeTableObject);
            //Table.CPU.DeleteTableObject += new Table.CPU.TableObject(CPU_DeleteTableObject);
            Table.CPU.ReloadTableList += new Table.CPU.TableObject(CPU_ReloadTableList);
        }

        ///// <summary>
        ///// 如果窗体关闭，记得要执行这个清理。因为数据库还没有关闭啊，那么CPU里面的事件就会重复罗。
        ///// </summary>
        //public void Clear()
        //{
        //    Table.CPU.ShenHeStoreSOrderS -= new Table.CPU.StoreOrderSShenHe(WuLiu);
        //}
        DispatcherTimer timer;
        private void InitRefreshDataEvent()
        {
            if (DoubleHConfig.AppConfig.ReloadDataTime <= 60)
                return;

            timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, DoubleHConfig.AppConfig.ReloadDataTime);
            timer.Tick += (ss, ee) => BeginBindData();
            timer.Start();
        }
    }
}